/*
 * File:   form_piecewise_linear_function.cpp
 * Author: dima
 *
 * Created on 14 Январь 2015 г., 15:54
 */
#include <QMessageBox>
#include "ui_form_piecewise_linear_function.h"
#include "form_piecewise_linear_function.h"

#include "ipd_img.h"
#include "ipd_piecewise_linear_function.h"
#include "ipd_exception.h"
#include "widget_curve_mouse.h"
#define step_color 30

form_piecewise_linear_function::form_piecewise_linear_function(ipd::ipd_img &img) : widget(new Ui::form_piecewise_linear_function()), original_image(img)
{
    widget->setupUi(this);

    widget->curve->set_size_XY(original_image.get_min_color(),original_image.get_max_color(), step_color, original_image.get_min_color(),original_image.get_max_color(), step_color);
    widget->curve->set_title_coordinates(QString("Brightness output"), QString("Brightness input"));

    convert_img = new ipd::ipd_img();
    piecewise_linear_function = new ipd::ipd_piecewise_linear_function(original_image, step_color);
    connect(widget->curve, SIGNAL(update_data(int, double, double)), this, SLOT(update_data(int, double, double)));
}

form_piecewise_linear_function::~form_piecewise_linear_function()
{
    delete piecewise_linear_function;
    delete convert_img;
    delete widget;
}

void form_piecewise_linear_function::init()// initialization class 
{
    double x;
    int size = piecewise_linear_function->get_count_points() - 1;
    for (int i = 0; i < size; i++)
    {
        x = i*step_color;
        widget->curve->add_value(x, x);
        piecewise_linear_function->set_value(i, x, x);
    }
    widget->curve->add_value(original_image.get_max_color(), original_image.get_max_color());
    piecewise_linear_function->set_value(size, original_image.get_max_color(), original_image.get_max_color());
    widget->curve->set_data();
}

void form_piecewise_linear_function::convert_image()
{
    try
    {
        piecewise_linear_function->convert_image(*convert_img);
        emit send_image(*convert_img);
    }
    catch (ipd::ipd_exception &except)
    {
        QMessageBox::critical(0, QString::fromUtf8(except.in_file().c_str()), QString::fromUtf8(except.what().c_str()), 0, 0);
    }
}

void form_piecewise_linear_function::update_data(int index, double x, double y)// update the data for the curve
{
    try
    {
        piecewise_linear_function->set_value(index, x, y);
    }
    catch (ipd::ipd_exception &except)
    {

    }
}